import { Component, OnInit } from '@angular/core';
import { ActionSheetController } from '@ionic/angular';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import {HttpClient,HttpHeaders} from "@angular/common/http";
import {environment} from 'src/environments/environment';
import { EncryptService } from '@services/encrypt.service';
import { AuthTokenService } from '@services/auth-token.service';
import { CommonResponse,VerificationType,ToastColor,CommonService,AppParam } from '@services/common-service.service';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
  selector: 'app-signin-sms',
  templateUrl: './signin-sms.page.html',
  styleUrls: ['./signin-sms.page.scss'],
})
export class SigninSmsPage implements OnInit {

  public consentAgreement:boolean = true;

  public appUser:any = {
    mobileNumber:'',
    verificationCode:'',
    countryCode:'86'
  }

  public sendView:boolean = true;

  public defaultSmsCountDown:number;

  public smsCountDown:number;

  public i18n:any;

  public validateForm:FormGroup;

  public loading:boolean = false;

  constructor(private router: Router,
    private actionSheetController: ActionSheetController,
    private http:HttpClient,
    private encryptService:EncryptService,
    private authTokenService: AuthTokenService,
    private commonService:CommonService) {
      this.i18n = this.commonService.initTranslate(['auth.signinSMS']); 
      this.validateForm = new FormGroup({
        'mobileNumber':new FormControl(this.appUser.mobileNumber,[
          Validators.required
        ]),
        'verificationCode':new FormControl('',[
          Validators.required
        ]),
        'countryCode':new FormControl(this.appUser.countryCode,[])
      });
      this.defaultSmsCountDown = parseInt(this.commonService.getAppParamFromCache(AppParam.SMS_COUNT_DOWN));
      this.smsCountDown = this.defaultSmsCountDown;
  }

  get mobileNumber(){return this.validateForm.get('mobileNumber');}

  get verificationCode(){return this.validateForm.get('verificationCode');}

  ngOnInit() {
    
  }

  changeConsentAgreement(){
    this.consentAgreement = !this.consentAgreement;
  }

  signUp(){
    this.validateForm.reset();
    this.router.navigate(['/auth/signin-first']);
  }

  sendVerificationCode(){
    if(!this.validateForm.value.mobileNumber){   
      this.commonService.commonToast(ToastColor.warning,this.i18n.mobileNumber_required);
      return false;
    }
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    var requestJson = {
      'mobileNumber':this.validateForm.value.mobileNumber,
      'appCode':environment.APP_CODE,
      'deviceId':this.authTokenService.getDeviceId(),
      'verificationType':VerificationType.LOGIN_SMS
    }
    var api = "/scm/app/sendAppVerificationCode.do";
    this.http.post(api,requestJson,httpOptions).subscribe((response) => {
      this.sendView = false;
      var id = setInterval(() => {
        this.smsCountDown--;
        if(this.smsCountDown == 0){
          this.smsCountDown = this.defaultSmsCountDown;
          clearInterval(id);
          this.sendView = true;
        }
      }, 1000);
    },(errorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
    });
  }

  async signInWithSMS(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    if(!this.consentAgreement){
      this.commonService.commonToast(ToastColor.warning,this.i18n.check_agree_agreement);
      return false;
    }
    this.loading = true;
    var api = "/scm/app/loginWithSMS.do";
    let currentTime = new Date().getTime().toString();
    let sign1 = this.encryptService.md5Ecrypt(this.validateForm.value.mobileNumber+this.validateForm.value.verificationCode+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.validateForm.value.mobileNumber+","+this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    this.http.post(api,{},httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        this.validateForm.reset();
        this.commonService.commonToast(ToastColor.success,this.i18n.login_success);
        this.authTokenService.login(response);
        if(response.responseBody.deviceChanged){
          this.router.navigate(['/auth/fingerprint-setup']);
        }else{
          this.router.navigate(['/tabs/home']);
        }
      }
      this.loading = false;
    },(errorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      this.loading = false;
    });
  }

  lookAgreement(){
    let navigationExtras: NavigationExtras = {
      queryParams: { 
        'onlyLook': true
      }
    };
    this.router.navigate(['/auth/agreement'],navigationExtras);
  }

  async presentActionSheet() {
    let actionSheetButton:Array<any> = [];
    let fingerprintButton = {
      text: this.i18n.fingerprint_login,
      role: '',
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-fingerprint']);
      }
    };
    if(this.authTokenService.getLoginToken() && this.authTokenService.getAppUserId()){
      actionSheetButton.push(fingerprintButton);
    }
    let otherButtons:Array<any> = [{
      text: this.i18n.user_password_login,
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-password']);
      }
    }, {
      text: this.i18n.switch_user_signup,
      icon: '',
      handler: () => {
        this.validateForm.reset();
        this.router.navigate(['/auth/signin-first']);
      }
    }, {
      text: this.i18n.cancel,
      icon: '',
      role: 'cancel',
      handler: () => {
        console.log('Cancel clicked');
      }
    }];
    actionSheetButton = actionSheetButton.concat(otherButtons);
    const actionSheet = await this.actionSheetController.create({
      header: '',
      buttons:actionSheetButton
    });
    await actionSheet.present();
  }

  inputMobileNumber(){
    this.validateForm.reset();
    this.router.navigate(['/auth/reset-pwd/input-mobile']);
  }

}
